//
//  ZCAssignCodeViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/20.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCAssignCodeViewController.h"
#import "ZCAssignCodeTableViewCell.h"
#import "ZCAssignCodeModel.h"
#import "ZCAssignCodeDetailViewController.h"
#import "UWRQViewController.h"


static NSString *assignCodeCellID = @"ZCAssignCodeTableViewCell";

@interface ZCAssignCodeViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate, uwRQDelegate>
@property (nonatomic, strong) UITableViewController *tableViewVC;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UISearchController *searchVC;
@property (nonatomic, strong) UIButton *qrButton;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCAssignCodeViewController
#pragma mark - 懒加载
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 40)];
        _searchView.backgroundColor = [UIColor whiteColor];
    }
    return _searchView;
}

- (UITableViewController *)tableViewVC {
    if (!_tableViewVC) {
        _tableViewVC = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
//        _tableViewVC.tableView.frame = CGRectMake(0, -20, SCREENWIDTH, SCREENHEIGHT);
        _tableViewVC.tableView.delegate = self;
        _tableViewVC.tableView.dataSource = self;
        _tableViewVC.tableView.showsVerticalScrollIndicator = NO;
        _tableViewVC.tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableViewVC.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableViewVC.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableViewVC.tableView.scrollIndicatorInsets = _tableViewVC.tableView.contentInset;
            _tableViewVC.tableView.estimatedRowHeight = 0;
            _tableViewVC.tableView.estimatedSectionFooterHeight = 0;
            _tableViewVC.tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableViewVC.tableView registerClass:[ZCAssignCodeTableViewCell class] forCellReuseIdentifier:assignCodeCellID];
        _tableViewVC.tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    }
    return _tableViewVC;
}

-(UIButton *)qrButton {
    if (!_qrButton) {
        _qrButton = [[UIButton alloc] init];
        [_qrButton setImage:[UIImage imageNamed:@"scanQR"] forState:UIControlStateNormal];
        [_qrButton addTarget:self action:@selector(qrCodeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _qrButton;
}

- (UISearchController *)searchVC {
    if (!_searchVC) {
        _searchVC = [[UISearchController alloc] initWithSearchResultsController:self.tableViewVC];
        _searchVC.hidesNavigationBarDuringPresentation = YES;
        _searchVC.searchBar.placeholder = @"请输入订单号/车架号";
        _searchVC.delegate = self;
        _searchVC.searchResultsUpdater = self;
        _searchVC.searchBar.delegate = self;
        [_searchVC.searchBar addSubview:self.qrButton];
        __weak typeof(self)weakSelf = self;
        [_qrButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(weakSelf.searchVC.searchBar.mas_centerY);
            make.right.mas_equalTo(weakSelf.searchVC.searchBar.mas_right).offset(-15);
        }];
    }
    return _searchVC;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToHome) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.title = @"快速赋码";
    self.view.backgroundColor = [UIColor whiteColor];
    self.definesPresentationContext = YES;
    [self.view addSubview:self.searchView];
    [self.searchView addSubview:self.searchVC.searchBar];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.searchVC.searchBar.text.length > 0) {
        [self.hud showAnimated:YES];
        [self loadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.hud) {
        [self.hud hideAnimated:YES];
        self.hud.mode = MBProgressHUDModeIndeterminate;
    }
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.searchVC.searchBar.text forKey:@"queryParam"];
    [params setObject:@(0) forKey:@"taskType"];
    [params setObject:@(1) forKey:@"pageNo"];
    [params setObject:@(10) forKey:@"pageSize"];
    NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
    if (originId.length > 0) {
        [params setObject:originId forKey:@"pointId"];
    }
    __weak typeof(self)weakSelf = self;
//    [self.hud showAnimated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:HomeSearch params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                [self.dataArray removeAllObjects];
                NSArray *array = responseObject[@"data"];
                for (NSDictionary *dataDic in array) {
                    ZCAssignCodeModel *assignCodeModel = [ZCAssignCodeModel yy_modelWithDictionary:dataDic];
                    [self.dataArray addObject:assignCodeModel];
                }
                [weakSelf.tableViewVC.tableView.mj_header endRefreshing];
                [weakSelf.tableViewVC.tableView reloadData];
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.hud showAnimated:YES];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                });
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableViewVC.tableView.mj_header endRefreshing];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud showAnimated:YES];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            });
        }];
    });
}

#pragma mark - 按钮点击
- (void)qrCodeButtonClick:(UIButton *)sender {
    UWRQViewController *rqVC = [[UWRQViewController alloc] init];
    rqVC.delegate = self;
    [self.navigationController pushViewController:rqVC animated:YES];
}

- (void)backToHome {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - ueRQDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *arr = [result componentsSeparatedByString:@","];
    NSString *keyId = [arr firstObject];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:keyId forKey:@"queryParam"];
    [param setObject:@(0) forKey:@"taskType"];
    NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
    if (originId.length > 0) {
        [param setObject:originId forKey:@"pointId"];
    }
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:SearchByQRCode params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                ZCAssignCodeDetailModel *detailModel = [ZCAssignCodeDetailModel yy_modelWithDictionary:responseObject[@"data"]];
                ZCAssignCodeDetailViewController *detailVC = [[ZCAssignCodeDetailViewController alloc] init];
                detailVC.releaseId = detailModel.releaseId;
                [weakSelf.navigationController pushViewController:detailVC animated:YES];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.hud.mode = MBProgressHUDModeIndeterminate;
    [self.hud showAnimated:YES];
    [self loadData];
}

#pragma mark - UISearchControllerDelegate
- (void)willPresentSearchController:(UISearchController *)searchController {
    self.qrButton.hidden = YES;
}

- (void)didDismissSearchController:(UISearchController *)searchController {
    self.qrButton.hidden = NO;
    [self.hud hideAnimated:YES];
}


#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (searchController.isActive) {
        
        searchController.searchBar.showsCancelButton = YES;
        UIButton *cancelButton = [searchController.searchBar valueForKey:@"cancelButton"];
        if (cancelButton) {
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            [cancelButton setTitleColor:ZCColor(0x000000, 0.87) forState:UIControlStateNormal];
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCAssignCodeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:assignCodeCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ZCAssignCodeModel *codeModel = (ZCAssignCodeModel *)self.dataArray[indexPath.section];
    cell.assignCodeModel = codeModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(360);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}


#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCAssignCodeDetailViewController *detailVC = [[ZCAssignCodeDetailViewController alloc] init];
    ZCAssignCodeModel *codeModel = (ZCAssignCodeModel *)self.dataArray[indexPath.section];
    detailVC.releaseId = codeModel.releaseId;
    [self.navigationController pushViewController:detailVC animated:YES];
}



@end
